/**
 * 图表工具类
 */

/**
 * 获取信用分饼图配置
 * @param {array} data 数据数组
 * @returns {object} ECharts配置
 */
export function getCreditPieChartConfig(data) {
  return {
    title: {
      text: '信用分维度分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}分 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: data.map(item => item.name)
    },
    series: [
      {
        name: '信用维度',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
}

/**
 * 获取信用分历史趋势图配置
 * @param {array} history 历史数据
 * @returns {object} ECharts配置
 */
export function getCreditTrendChartConfig(history) {
  const dates = history.map(item => item.date)
  const scores = history.map(item => item.score)
  
  return {
    title: {
      text: '信用分变化趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0]
        return `${data.axisValue}<br/>信用分: ${data.value}分`
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      min: function(value) {
        return Math.max(350, value.min - 20)
      },
      max: function(value) {
        return Math.min(850, value.max + 20)
      }
    },
    series: [
      {
        name: '信用分',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#409EFF',
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        },
        data: scores
      }
    ]
  }
}

/**
 * 获取雷达图配置
 * @param {object} radarData 雷达图数据
 * @returns {object} ECharts配置
 */
export function getRadarChartConfig(radarData) {
  return {
    title: {
      text: '信用能力雷达图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: radarData.indicators,
      shape: 'circle',
      splitNumber: 5,
      name: {
        textStyle: {
          color: '#666'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#e6e6e6'
        }
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['rgba(64, 158, 255, 0.05)', 'rgba(64, 158, 255, 0.1)']
        }
      }
    },
    series: [
      {
        type: 'radar',
        data: radarData.data
      }
    ]
  }
}

/**
 * 获取管理员仪表板核心指标图表配置
 * @param {object} stats 统计数据
 * @returns {object} 配置对象
 */
export function getDashboardStatsConfig(stats) {
  return {
    userGrowth: {
      title: '用户增长',
      value: stats.totalUsers,
      growth: stats.userGrowth,
      icon: 'el-icon-user',
      color: '#409EFF'
    },
    creditScore: {
      title: '平均信用分',
      value: stats.avgCreditScore,
      growth: stats.scoreGrowth,
      icon: 'el-icon-star-on',
      color: '#67C23A'
    },
    serviceUsage: {
      title: '服务使用量',
      value: stats.totalServices,
      growth: stats.serviceGrowth,
      icon: 'el-icon-goods',
      color: '#E6A23C'
    },
    revenue: {
      title: '总收入',
      value: stats.totalRevenue,
      growth: stats.revenueGrowth,
      icon: 'el-icon-money',
      color: '#F56C6C'
    }
  }
}

/**
 * 获取柱状图配置
 * @param {object} data 数据
 * @param {object} options 选项
 * @returns {object} ECharts配置
 */
export function getBarChartConfig(data, options = {}) {
  const defaultOptions = {
    title: '数据统计',
    xAxisData: [],
    seriesData: [],
    color: '#409EFF'
  }
  
  const config = { ...defaultOptions, ...options }
  
  return {
    title: {
      text: config.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: config.xAxisData,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: config.color,
          borderRadius: [4, 4, 0, 0]
        },
        data: config.seriesData
      }
    ]
  }
}

/**
 * 获取多系列折线图配置
 * @param {object} data 数据
 * @param {object} options 选项
 * @returns {object} ECharts配置
 */
export function getMultiLineChartConfig(data, options = {}) {
  const defaultOptions = {
    title: '趋势对比',
    legend: [],
    xAxisData: [],
    series: []
  }
  
  const config = { ...defaultOptions, ...options }
  
  return {
    title: {
      text: config.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: config.legend,
      top: 30
    },
    xAxis: {
      type: 'category',
      data: config.xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: config.series.map(item => ({
      ...item,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6
    }))
  }
}

/**
 * 获取环形进度图配置
 * @param {number} percentage 百分比
 * @param {string} title 标题
 * @param {string} color 颜色
 * @returns {object} ECharts配置
 */
export function getRingProgressConfig(percentage, title, color = '#409EFF') {
  return {
    title: {
      text: `${percentage}%`,
      subtext: title,
      left: 'center',
      top: 'middle',
      textStyle: {
        fontSize: 24,
        fontWeight: 'bold',
        color: color
      },
      subtextStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['70%', '90%'],
        avoidLabelOverlap: false,
        silent: true,
        label: {
          show: false
        },
        data: [
          {
            value: percentage,
            itemStyle: {
              color: color
            }
          },
          {
            value: 100 - percentage,
            itemStyle: {
              color: '#f0f0f0'
            }
          }
        ]
      }
    ]
  }
}

/**
 * 获取地图配置（用于用户分布）
 * @param {array} data 地区数据
 * @returns {object} ECharts配置
 */
export function getMapChartConfig(data) {
  return {
    title: {
      text: '用户地区分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}人'
    },
    visualMap: {
      min: 0,
      max: Math.max(...data.map(item => item.value)),
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#e0f3ff', '#409EFF']
      }
    },
    series: [
      {
        name: '用户数量',
        type: 'map',
        map: 'china',
        roam: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          itemStyle: {
            areaColor: '#389BB7'
          }
        },
        data: data
      }
    ]
  }
}

/**
 * 获取仪表盘配置
 * @param {number} value 当前值
 * @param {string} title 标题
 * @param {number} max 最大值
 * @returns {object} ECharts配置
 */
export function getGaugeChartConfig(value, title, max = 100) {
  return {
    series: [
      {
        name: title,
        type: 'gauge',
        min: 0,
        max: max,
        splitNumber: 5,
        radius: '80%',
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.2, '#ff4757'],
              [0.4, '#ffa502'],
              [0.6, '#f39c12'],
              [0.8, '#2ed573'],
              [1, '#1e90ff']
            ]
          }
        },
        axisLabel: {
          fontSize: 12,
          color: '#666'
        },
        axisTick: {
          length: 8,
          lineStyle: {
            color: 'auto'
          }
        },
        splitLine: {
          length: 12,
          lineStyle: {
            color: 'auto'
          }
        },
        pointer: {
          width: 5
        },
        title: {
          fontSize: 14
        },
        detail: {
          fontSize: 20,
          fontWeight: 'bold',
          formatter: '{value}'
        },
        data: [
          {
            value: value,
            name: title
          }
        ]
      }
    ]
  }
}

/**
 * 通用图表响应式配置
 * @param {object} chart ECharts实例
 */
export function makeChartResponsive(chart) {
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

/**
 * 获取图表通用颜色配置
 */
export const CHART_COLORS = {
  primary: '#409EFF',
  success: '#67C23A',
  warning: '#E6A23C',
  danger: '#F56C6C',
  info: '#909399',
  light: '#C0C4CC',
  dark: '#303133'
}

/**
 * 获取图表主题配置
 */
export function getChartTheme() {
  return {
    color: [
      CHART_COLORS.primary,
      CHART_COLORS.success,
      CHART_COLORS.warning,
      CHART_COLORS.danger,
      CHART_COLORS.info
    ],
    backgroundColor: 'transparent',
    textStyle: {
      color: '#333'
    },
    title: {
      textStyle: {
        color: '#333'
      }
    }
  }
} 